package club.baimahu.pencil.miaosha.rocketmq;


import com.sun.xml.internal.bind.v2.runtime.RuntimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PropertiesLoaderUtils;

@Slf4j
@Configuration
public class Producer {

    private DefaultMQProducer defaultMQProducer;

    @Value("${rocketmq.producer.namesrvAddr}")
    public String namesrvAddr;

    @Value("${rocketmq.producer.groupName}")
    public String groupName;

    @Bean
    public DefaultMQProducer defaultMQProducer() throws MQClientException {

        DefaultMQProducer producer = new DefaultMQProducer(groupName);
        producer.setInstanceName(producer+"-" +System.currentTimeMillis());
        producer.setNamesrvAddr(namesrvAddr);
        producer.start();
        this.defaultMQProducer = producer;
        registerHook();
        return producer;

    }

    public void destroy(){

        if(defaultMQProducer != null){
            String instanceName = defaultMQProducer.getInstanceName();
            log.info("start destroy RocketMQ producer instance[{}]",instanceName);
            defaultMQProducer.shutdown();
            log.info("finish destroy RocketMQ producer instance[{}]",instanceName);
        }
    }

    private void registerHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                destroy();
            }
        }));
    }


}
